﻿
using Cl.Utils.Helper;
using Cl.Utils.Primitives.Enum;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cl.Utils.Signalr.Hub.HubRegister
{
    /// <summary>
    /// 全局signalr,登陆的时候会记录。统计在线人数的时候需要group userId
    /// </summary>
    public class GlobalHub : Microsoft.AspNetCore.SignalR.Hub
    {

        public override async Task OnConnectedAsync()
        {
            try
            {



                #region 验证token验证的signalr连接

                var httpContext = Context.GetHttpContext();
                if (httpContext != null)
                {
                    var token = httpContext.Request.Query["token"];

                    // 检查token是否存在且非空
                    if (string.IsNullOrEmpty(token))
                    {
                        // 如果没有token或为空，则拒绝连接
                        await Clients.Caller.SendAsync("DenyConnection", "缺少必要的token参数");
                        return;
                    }

                    // 在这里可以添加额外的token验证逻辑，比如验证token的有效性
                    var accountData = JwtHelper.JWTDecode(token);
                    if (accountData == null)
                    {
                        await Clients.Caller.SendAsync("DenyConnection", "缺少必要的token参数");
                        return;
                    }

                    // 如果token验证通过或无需验证，继续处理连接
                    string ipAddress = UtilHelper.GetClientIpAddress(httpContext.Request);

                    GlobalService.SignalrConnectedLists.Add(new ChatInfoData()
                    {
                        ConnectionId = Context.ConnectionId,
                        UserId = accountData.UserId,
                        IpAddress = ipAddress

                    });

                    await base.OnConnectedAsync();
                }

                #endregion

                #region 不含token验证的signalr连接

                //if (Context != null && Context.ConnectionId != null)
                //{
                //    var httpContext = Context.GetHttpContext();
                //    string ipAddress = UtilHelper.GetClientIpAddress(httpContext.Request);
                //    GlobalLimsService.ConnectedTaskInfos.Add(new ChatInfoData()
                //    {
                //        ConnectionId = Context.ConnectionId,
                //        IpAddress = ipAddress

                //    });
                //}

                //await base.OnConnectedAsync();

                #endregion

            }
            catch (Exception ex)
            {
                LoggerHelper.Error(LogEnum.Common, $"OnConnectedAsync,{ex.Message}");

            }
        }

        public override async Task OnDisconnectedAsync(Exception? exception)
        {
            try
            {


                var deleteData = GlobalService.SignalrConnectedLists.FirstOrDefault(x => x != null && x.ConnectionId != null && x.ConnectionId == Context.ConnectionId);
                if (deleteData != null)
                    GlobalService.SignalrConnectedLists.Remove(deleteData);

                await base.OnDisconnectedAsync(exception);


            }
            catch (Exception ex)
            {
                LoggerHelper.Error(LogEnum.Common, $"OnDisconnectedAsync,{ex.Message}");
            }
        }


        //public async Task SendMessage(string user, string message)
        //{
        //    await Clients.All.SendAsync("ReceiveMessage", user, message);
        //}

    }
}
